package com.yc.fresh.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yc.fresh.bean.TypeInfo;
import com.yc.fresh.service.ITypeInfoService;
import com.yc.fresh.util.StringUtil;
import com.yc.fresh.vo.ResultVO;

@RestController
@RequestMapping("/type")
public class TypeInfoController {
	@Autowired
	private ITypeInfoService typeInfoService;
	
	@PostMapping("/add")
	public ResultVO add(TypeInfo type,@RequestParam("photo") MultipartFile pic, HttpServletRequest request) {
		if(pic.isEmpty()) {
			return new ResultVO(501, "图片为空");
		}
		try {
			String savePath = "pics";
			String temp = request.getServletContext().getInitParameter("uploadPath");//获取用户配置路径
			if(!StringUtil.checkNull(temp)) {
				savePath = temp;
			}
			
			String path = request.getServletContext().getRealPath("");//获取tomcat在服务器中的绝对路径
			
			savePath += "/" + new Date().getTime() + "_" + pic.getOriginalFilename();//重命名上传的文件
			
			File dest = new File(new File(path).getParentFile(), savePath);
			
			//将本地文件保存到服务器
			pic.transferTo(dest);
			type.setPic(savePath);
		}catch(IllegalStateException e){
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
		int result = typeInfoService.add(type);
		if(result > 0) {
			return new ResultVO(200, "成功");
		}
		return new ResultVO(500, "失败");
	}
	/**
	 * 处理后端管理员查询所有商品类型信息
	 * @return
	 */
	@GetMapping("/findAll")
	public ResultVO findAll(){
		List<TypeInfo> list = typeInfoService.findAll();
		if(list == null || list.isEmpty()) {
			return new ResultVO(601,"数据为空");
		}
		return new ResultVO(200,"成功",list);
	}
	/**
	 * 处理前端用户查询所有可用的商品类型信息
	 * @return
	 */
	@GetMapping("/finds")
	public ResultVO finds(){
		List<TypeInfo> list = typeInfoService.finds();
		if(list == null || list.isEmpty()) {
			return new ResultVO(601,"数据为空");
		}
		return new ResultVO(200,"成功",list);
	}
	
	@PostMapping("/update")
	public ResultVO update(TypeInfo tf){
		int result = typeInfoService.update(tf);
		if(result > 0) {
			return new ResultVO(200,"成功");
		}
		return new ResultVO(500,"失败");
	}
}
